/*
MIT License

Copyright (c) 2009 NewsGator Technologies Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*
* Library for handling images in NewsGator Buzz
* Requires JQuery
*/

var ngImageUtils = (function() {
	var $ = jQuery;

	return {
		//Attempt to find the best photo from the post, ie, the closest to the given size
		//also applies some magic to Flickr and SmugMug photos to get the "medium" size
		//returns an array of objects like {url:"http://someImageUrl", height:123, width:123}
		pickPhoto: function(post, maxWidth, maxHeight) {
			var candidates = this.findPhotos(post);

			if (!candidates || candidates.length == 0) {
				return null;
			}

			function cleanSize(size) {
				try {
					if (!size) { return 0; }
					if (!isNaN(size)) { return size; }
					size = size.replace(/^\s*(\d+)/, "$1");
					if (size && size.length > 0) {
						return parseInt(size, 10);
					} else {
						return 0;
					}
				} catch (e) {
					return 0;
				}
			}

			function calcFitness(h, w) {
				var hFit = (h > 0 ? (Math.abs(maxHeight - h) / maxHeight) : 0.25);
				var wFit = (w > 0 ? (Math.abs(maxWidth - w) / maxWidth) : 0.25);
				return Math.min(hFit, wFit);
			}

			//compute a fitness for each image based on reported size
			$(candidates).each(function() {
				var h = cleanSize(this.height);
				var w = cleanSize(this.width);
				this.fit = calcFitness(h, w);
			});

			//see if any look like flickr/smugmug naming conventions and return a size-m version of it
			var re = /([_\-])(O|M|S|L|(?:Th))\.(jpe?g)/i;
			$(candidates).each(function() {
				if ((!this.h || !this.w) && (/flickr\.com/i).test(this.url)) {
					if (re.test(this.url)) {
						var size = (RegExp.$2 || "").toUpperCase();
						switch (size) {
							case "O":
								//for original size we just have to guess
								this.w = 2500;
								this.h = 2000;
								break;
							case "M":
								this.w = 240;
								this.h = 160;
								break;
							case "T":
								this.w = 100;
								this.h = 67;
								break;
							case "S":
								this.w = 75;
								this.h = 75;
								break;
						}
					}
				}

				if ((/smugmug\.com/i).test(this.url)) {
					if (re.test(this.url)) {
						var size = (RegExp.$2 || "").toUpperCase();
						switch (size) {
							case "O":
								//for original size we just have to guess
								this.w = 2500;
								this.h = 2000;
								break;
							case "L":
								this.h = this.w = 800;
								break;
							case "M":
								this.h = this.w = 600;
								break;
							case "S":
								this.h = this.w = 400;
								break;
							case "TH":
								this.h = this.w = 200;
								break;
							default:
								break;
						}
						if (size && size != "M") {
							var newUrl = this.url.replace(re, "$1M.$3");
							candidates.unshift({ url: newUrl, h: 600, w: 600, fit: calcFitness(600, 600) });
						}
					}
				}

				if (this.h && this.w) {
					this.fit = calcFitness(this.h, this.w);
				}
			});

			//Sort off the fitness
			candidates.sort(function(a, b) {
				return a.fit - b.fit;
			});

			//return the best one
			return candidates[0];
		},

		//Attempt to extract all available "photos" from a post (basically JPEG images)
		//returns an array of objects like {url:"http://someImageUrl", height:123, width:123}
		findPhotos: function(post) {
			var pArr = [];
			if (post.MediaRSS) {
				var mrss = post.MediaRSS;
				if (mrss.Thumbnail && mrss.Thumbnail.Url) {
					var th = mrss.Thumbnail;
					pArr.push({ url: th.Url, width: th.Width, height: th.Height });
				}

				if (mrss.Contents) {
					$(mrss.Contents).each(function() {
						if ((this.Type && (/^image/i).test(this.Type)) || (/\.(jpg)|(jpeg)/i).test(this.Url)) {
							pArr.push({ url: this.Url, height: this.Height, width: this.Width });
						}
					});
				}
			}

			if (post.EnclosureUrl && (!post.EnclosureType || (/^image/i).test(post.EnclosureType))) {
				pArr.push({ url: post.EnclosureUrl, width: 0, height: 0 });
			}

			//If there are images in the description, grab those
			if (/<img/i.test(post.Description)) {
				var node = ng_nodeProcessor.htmlToNodes(post.Description, true);
				$("img", node).each(function() {
					var h = this.height || this.style.height || $(this).height();
					var w = this.width || this.style.width || $(this).width();
					pArr.push({ url: this.src, width: w, height: h });
				});
			}

			return pArr;
		},

		//Does some magic to try to figure out the actual dimensions of a photo and then scale it intelligently
		//note that the image loading must be complete before this works!
		scaleImage: function(imgElem, maxWidth, maxHeight) {
			maxWidth = maxWidth || 150;
			maxHeight = maxHeight || 150;
			var parent = imgElem.parentNode;
			try {
				var img = $(imgElem);
				var div = document.createElement("div");
				document.body.appendChild(div);
				$(div).css({
					position: "absolute",
					height: "1px",
					width: "1px",
					left: "0px",
					top: "0px",
					overflow: "hidden"
				});

				parent.removeChild(imgElem);
				div.appendChild(imgElem);

				var h = img.height();
				var w = img.width();

				var sf = maxHeight / h;
				sf = Math.min(sf, (maxWidth / w));

				if (sf != 1) {
					img.height(Math.floor(h * sf));
					img.width(Math.floor(w * sf));
				}

				imgElem.parentNode.removeChild(imgElem);
				parent.appendChild(imgElem);
				document.body.removeChild(div);
				return;
			} catch (e) {
				if (parent != imgElem.parentNode) {
					imgElem.parentNode.removeChild(imgElem);
					parent.appendChild(imgElem);
				}
			}
		}

	};
})();
